<link rel="stylesheet" href="style/extra.css">

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/app-route/app-route.html">
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../bower_components/iron-input/iron-input.html">
<link rel="import" href="../bower_components/paper-icon-button/paper-icon-button.html">

<link rel="import" href="elements/codelabs-card.html">
<link rel="import" href="elements/tutorials-app-header.html">
<!-- <link rel="import" href="elements/tutorials-filters.html"> -->

<dom-module id="codelabs-index">

  <template>

    <style include="iron-flex iron-flex-alignment">
      :host {
        display: block;
      }

      paper-tabs {
        --paper-tabs-selection-bar-color: var(--app-primary-color);
      }

      paper-tab {
        --paper-tab-ink: var(--app-primary-color);
      }

      input[type='search'] {
        background-color: white;
        border: 1px solid var(--color-mid-light);
        border-radius: 0;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12) inset;
        box-sizing: border-box;
        font-family:  Helvetica, Arial;
        font-size: 1em;
        font-weight: 300;
        height: 44px;
        line-height: 24px;
        margin-bottom: 1em;
        margin-right: -46px;
        margin-top: 1.5em;
        max-width: 958px;
        outline-offset: -2px;
        padding: 6px 46px 6px 10px;
        width: 100%;
        -webkit-appearance: none;
      }

      @media only screen and (min-width: 769px) {
        input[type='search'] {
          width: 480px;
        }
      }

      input[type='search']:focus {
        border-color: var(--tertiary-text-color);
        color: var(--tertiary-text-color);
      }

      paper-icon-button.search {
        color: var(--color-mid-light);
      }

      paper-icon-button.search:hover {
        color: var(--tertiary-text-color);
      }

      ::-webkit-input-placeholder { /* Chrome/Opera/Safari */
        color: var(--secondary-text-color);
      }

      ::-moz-placeholder { /* Firefox 19+ */
        color: var(--secondary-text-color);
      }

      :-ms-input-placeholder { /* IE 10+ */
        color: var(--secondary-text-color);
      }

      :-moz-placeholder { /* Firefox 18- */
        color: var(--secondary-text-color);
      }

      :focus::-webkit-input-placeholder { /* Chrome/Opera/Safari */
        color: var(--tertiary-text-color);
      }

      :focus::-moz-placeholder { /* Firefox 19+ */
        color: var(--tertiary-text-color);
      }

      :focus:-ms-input-placeholder { /* IE 10+ */
        color: var(--tertiary-text-color);
      }

      :focus:-moz-placeholder { /* Firefox 18- */
        color: var(--tertiary-text-color);
      }

      .content {
        margin: 0 auto;
        max-width: 980px;
        padding: 10px;
      }

      .intro {
        box-sizing: border-box;
        clear: both;
        display: block;
        font-family: Helvetica, Arial;
        height: 100%;
        overflow: hidden;
        padding: 0 10px 10px;
        position: relative;
        width: 100%;
      }

      .intro h1 {
        font-size: 2.8125em;
        font-weight: 300;
      }

      .intro p {
        max-width: 620px;
      }

      .intro a {
        color: var(--app-primary-color);
      }

      h2 {
        display: block;
        font-size: 1.625em;
        font-weight: 300;
        line-height: 1.3;
        margin-bottom: 2.25em;
        width: 100%;
      }

      h3 {
        display: block;
        font-size: 1.4375em;
        font-weight: 300;
        line-height: 1.3;
        width: 100%;
      }

      .heading-results {
        margin-bottom: 1em;
      }

      @media only screen and (min-width: 769px) {
        .heading-results {
          margin-bottom: 1.75em;
        }
      }

      @media only screen and (min-width: 769px) {
        .heading-results {
          margin-bottom: 2em;
        }
      }

      .heading-results__highlight {
        font-weight: normal;
      }

      .no-results {
        padding-left: 10px;
      }

      .no-results h2 {
        margin-bottom: 1em;
      }

      codelabs-card {
        margin: 10px;
        width: 100%;
      }

      @media only screen and (min-width: 625px) {
        codelabs-card {
          width: calc(50% - 20px);
        }
      }

      @media only screen and (min-width: 901px) {
        codelabs-card {
          width: calc(33.3% - 20px);
        }
      }

      .event-wrapper {
        background-color: white;
        padding: 10px;
      }

      .event-logo {
        min-width: 200px;
      }

      .event-description {
        margin-left: 20px;
      }

      a.codelabs-index {
        text-decoration: none;
      }

      a.codelabs-index:hover {
        text-decoration: underline;
      }

      .footer {
        border-top: 1px solid #cdcdcd;
        font-size: 0.875rem;
        line-height: 1.5;
        margin-top: 2rem;
        padding: 1rem 0 2rem;
      }

      .footer > p {
        box-sizing: border-box;
        margin: 2rem auto;
        max-width: 1000px;
        padding: 0 20px;
      }

      .footer__nav {
        box-sizing: border-box;
        margin: 1rem auto;
        max-width: 1000px;
        padding: 0 20px;
      }

      .footer__links {
        list-style-type: none;
        padding: 0;
      }

      .footer__item {
        display: inline-block;
        margin-right: 0.5rem;
      }

      .footer__item::after {
        content: '\00b7';
        display: inline-block;
        font-size: 1em;
        margin-left: 0.5rem;
      }

      .footer__item:last-child::after {
        display: none;
      }

      .footer__link {
        color: #000;
      }

      .footer__link:visited {
        color: #000;
      }
    </style>

    <app-route
      route="{{route}}"
      pattern="/:event"
      data="{{routeData}}"></app-route>

    <div class="layout vertical">
      <tutorials-app-header class="rong-tutorials-header"></tutorials-app-header>
      <div>
        <template is="dom-if" if="{{currentEvent.id}}">
          <header class="horizontal layout event-wrapper">
            <img class="event-logo" src="/images/events/{{currentEvent.logo}}" />
            <div class="event-description">
              <h1>{{currentEvent.name}}</h1>
              <p>{{currentEvent.description}}</p>
            </div>
          </div>
        </template>
        <div class="content rong-content-box">
          <div class="rong-wrap-outer">
            <div class="wrap intro rong-wrap-box">
              <h3>融云帮助教程</h3>
              <p>融云教程示例包含演示代码、说明，每个教程均可帮助开发者构建一个简单、小型的应用，用来辅助开发者集成融云能力，教程涉及广泛，例如 RTC、IM 并且包含 Android、iOS、Web 多平台教程，希望对融云开发者朋友有所帮助</p>
              <div class="rong-search-box">
                <label class="accessibility-aid" for="edit-keys" hidden="hidden">Search</label>
                <input id="edit-keys" type="search" placeholder="输入关键字查询..." is="iron-input" bind-value="{{filterSearch}}" />
                <paper-icon-button class="search" icon="search"></paper-icon-button>
                <template is="dom-if" if="[[filterSearch]]">
                  <h2 class="heading-results">
                    </span> 搜索关键字 <span class="heading-results__highlight">[[filterSearch]]</span>
                    结果为 <span class="heading-results__highlight">[[searchResultCount]] 条
                  </h2>
                </template>
              </div>
              <div>
          </div>
              <!-- <tutorials-filters
                selected-category="{{filterCategory}}"
                selected-sort="{{filterSort}}"
                selected-user="{{filterUser}}"
                >
              </tutorials-filters> -->
            </div>
          </div>

          <div class="horizontal layout end">
            <div class="flex"></div>
          </div>
          <div class="horizontal layout wrap rong-codelabs-box">
            <template is="dom-repeat" items="[[filteredTutorials]]" sort="[[_getSortFunction(filterSort)]]">
              <codelabs-card heading="[[item.title]]" summary="[[item.summary]]" category="[[item.category]]"
                            difficulty="[[item.difficulty]]" duration="[[item.duration}}" tags="[[item.tags]]"
                            published="[[item.published]]" url="[[item.url]]" platform="[[item.platform]]"
                            ></codelabs-card>
            </template>
            <template is="dom-if" if="[[isEmpty]]">
              <div class="no-results">
                <h2>没有找到符合结果</h2>
                <h3>可按以下方式尝试:</h3>
                <ul>
                  <li>修改搜索关键字</li>
                  <li>使用关键词搜索</li>
                </ul>
              </div>
            </template>
          </div>
        </div>
        <footer class="footer">
          <nav class="footer__nav">
            <ul class="footer__links">
              <li class="footer__item">
                Copyright 2019 RongCloud
              </li>
              <li class="footer__item">
                <a class="footer__link" target="_blank" href="https://www.rongcloud.cn">融云官网</a>
              </li>
              <li class="footer__item">
                <a class="footer__link" target="_blank" href="https://docs.rongcloud.cn">文档中心</a>
              </li>
              <li class="footer__item">
                <a class="footer__link" target="_blank" href="https://developer.rongcloud.cn">开发者后台</a>
              </li>
            </ul>
          </nav>
        </footer>
      </div>
    </div>
  </template>

  <script>

    Polymer({

      is: 'codelabs-index',

      properties: {
        categoriesmap: Object,
        codelabs: {
          type: Array,
          notify: true,
        },
        eventsmap: Object,
        searchKeywords: {
          type: Array,
          notify: true,
          computed: '_searchKeywords(filterSearch)',
        },
        categories: {
          type: Array,
          computed: '_buildcategories(categoriesmap)',
        },
        route: String,
        filterCategory: {
          type: String,
          value: '',
          notify: true,
        },
        filterEvent: {
          type: Object,
          value: {},
          notify: true,
          computed: '_eventChanged(routeData.event, eventsmap)',
        },
        filterSort: {
          type: String,
          value: 'published-desc',
          notify: true,
        },
        filterUser: {
          type: String,
          value: '',
          notify: true,
        },
        filterSearch: {
          type: String,
          notify: true,
        },
        filteredTutorials: {
          type: Array,
          notify: true,
        },
        isEmpty: {
          type: Boolean,
          notify: true,
          computed: '_isEmpty(filteredTutorials)',
        },
        isLoading: Boolean,
        routeData: Object,
        searchResultCount: {
          type: Number,
          value: 0,
          notify: true,
        },
      },

      observers: [
        '_getFilteredTutorials(codelabs, searchKeywords, filterEvent, filterCategory, filterUser)', // eslint-disable-line
      ],

      attached: function() {
        this.updateMetadata();
      },

      ready: function() {
        if (this.route.__queryParams['q']) {
          this.filterSearch = this.route.__queryParams['q'];
        }
      },

      updateMetadata: function() {
        this.fire('app-metadata', {
          title: 'RongCloud Tutorials',
          description: `RongCloud Tutorials`, // eslint-disable-line
        });
      },

      _getSortFunction: function(sortOption) {
        switch(sortOption) {
          case 'published-asc':
            return function(a, b) {
              return (a.published > b.published ? 1 : -1);
            };
          case 'published-desc':
            return function(a, b) {
              return (a.published < b.published ? 1 : -1);
            };
          case 'duration-asc':
            return function(a, b) {
              return (a.duration > b.duration ? 1 : -1);
            };
          case 'duration-desc':
            return function(a, b) {
              return (a.duration < b.duration ? 1 : -1);
            };
          case 'difficulty-desc':
            return function(a, b) {
              return (a.difficulty < b.difficulty ? 1 : -1);
            };
          case 'difficulty-asc':
            return function(a, b) {
              return (a.difficulty > b.difficulty ? 1 : -1);
            };
        };
      },

      _getFilteredTutorials: function(
        tutorials, searchKeywords, currentEvent, currentCategory, currentUser
      ) {
        if (tutorials === null) {
          return [];
        }
        if (searchKeywords.length > 0) {
          tutorials = tutorials.filter(
            this._getSearchFilterFunction(searchKeywords)
          );
        }
        this.searchResultCount = tutorials.length;
        if (
          currentEvent !== '' ||
          currentCategory !== '' ||
          currentUser !== ''
        ) {
          tutorials = tutorials.filter(this._getFilterFunction(
            currentEvent, currentCategory, currentUser
          ));
        }
        this.filteredTutorials = tutorials;
        return tutorials;
      },

      _getSearchFilterFunction: function(searchKeywords) {
        return function(item) {
          let title = item.title.toLowerCase();
          let summary = item.summary.toLowerCase();
          let category = item.category[0].toLowerCase();
          let tags = item.tags;

          let shouldShow = true;
          searchKeywords.forEach(function(searchterm) {
            if (searchterm === '') {
              return;
            }
            searchterm = searchterm.toLowerCase();
            let searchtermFound = false;

            if (
              title.indexOf(searchterm) > -1 ||
              summary.indexOf(searchterm) > -1 ||
              category.indexOf(searchterm) > -1
            ) {
              searchtermFound = true;
              return;
            }

            tags.forEach(function(tag) {
              if (tag.toLowerCase().indexOf(searchterm) > -1) {
                searchtermFound = true;
                return;
              }
            }, this);
            shouldShow = shouldShow && searchtermFound;
          }, this);
          return shouldShow;
        };
      },

      _getFilterFunction: function(currentEvent, currentCategory, currentUser) {
        return function(item) {
          let category = item.category[0].toLowerCase();
          let tags = item.tags;

          // filter by event matching
          if (currentEvent.id && tags.indexOf(currentEvent.id) < 0) {
            return false;
          }

          // filter by category
          if (currentCategory !== '' && currentCategory !== category) {
            return false;
          }

          // TODO: filter by user

          return true;
        };
      },

      _isEmpty: function(results) {
        return results.length <= 0;
      },

      _eventChanged: function(eventID, eventsmap) {
        // FIXME (if upstream solution)
        // as we data-bind "subroute", even when not active, the view in map
        // /codelabs/codelab_id -> codelab_id matches :events and
        // return invalid content
        // escape if we are not current view
        if (!this.classList.contains('iron-selected')) {
          return;
        }
        if (eventID == 'web') {
          return {};
        }
        let currentEvent = {
          'id': eventID,
        };
        currentEvent.name = eventsmap[eventID].name;
        currentEvent.logo = eventsmap[eventID].logo;
        currentEvent.description = eventsmap[eventID].description;
        return currentEvent;
      },

      _searchKeywords: function(searchString) {
        if (searchString.length > 0) {
          return searchString.split(' ');
        }
        return [];
      },

      _buildcategories: function(categoriesmap) {
        let newcategories = Object.keys(categoriesmap).sort();
        newcategories.unshift('All');
        let indexunknown = newcategories.indexOf('unknown');
        if (indexunknown > -1) {
          newcategories.splice(indexunknown, 1);
        }
        return newcategories;
      },
    });

  </script>

</dom-module>
